﻿using BYSJ.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace BYSJ.EFDAL
{
    public class BaseDal<T> where T : class ,new()
    {
        private readonly ModelContainer db;
      
        public BaseDal()
        {
            db = DbContextFactory.dbEntities();
        }


        //DRY
        #region CUD

        public T Add(T entity)
        {
            db.Set<T>().Add(entity);
            //db.SaveChanges();//自动增长的主键，会自动赋值到  属性上去。
            return entity;
        }

        public bool Update(T entity)
        {
            db.Entry(entity).State = EntityState.Modified;
            //\return db.SaveChanges() > 0;
            return true;

        }

        public bool Delete(T entity)
        {
            db.Entry(entity).State = EntityState.Deleted;
            //db.SaveChanges();
            //return db.SaveChanges() > 0;
            return true;
        }
        #endregion

        #region 查询

        public IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda)
        {
            //db.Set<UserInfo>().Where(u => u.ID > 10).Select(u => u);

            return db.Set<T>().Where(whereLambda).AsQueryable();
        }

        //分页
        public IQueryable<T> LoadPageEntities<S>(int pageSize, int pageIndex,
                                                  out int totalCount,
            Expression<Func<T, bool>> whereLambda, bool isAsc, Expression<Func<T, S>> orderBy)
        {
            IQueryable<T> temp = db.Set<T>().Where(whereLambda).AsQueryable();

            totalCount = temp.Count();

            if (isAsc)
            {
                temp = temp.OrderBy(orderBy)
                           .Skip(pageSize * (pageIndex - 1))
                           .Take(pageSize).AsQueryable();
            }
            else
            {
                temp = temp.OrderByDescending(orderBy)
                          .Skip(pageSize * (pageIndex - 1))
                          .Take(pageSize).AsQueryable();
            }

            return temp;
        }

        #endregion
        #region 提交 +save()
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="ValidateOnSaveEnabled">是否打开验证</param>
        /// <returns></returns>
        public int SaveChanges()
        {
            db.Configuration.ValidateOnSaveEnabled = false;
            return db.SaveChanges();
        }

        #endregion
    }
}
